package core;

import branch.Branch;
import fileoperation.FileDeletion;
import repository.Repository;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class JitBranch {
    /**
     * show all branch name
     */
    public static void printBranch() throws IOException {
        File dir = new File(Branch.path);
        File[] file_list = dir.listFiles();
        ArrayList<String> branches = new ArrayList<>();
        assert file_list != null;
        for (File file : file_list) {
            branches.add(file.getName());
        }
        String currentBranch = Branch.getCurrentBranchName();
        for (String branch : branches) {
            if (currentBranch.equals(branch))
                System.out.print("* ");
            else
                System.out.print("  ");
            System.out.println(branch);
        }
    }

    /**
     * constructing new branch
     */
    public static void branch(String branchName) throws IOException {
        if (Branch.branchExist(branchName)) {
            System.out.println("Branch " + branchName + " already exists.");
            return;
        }
        Branch branch = new Branch(branchName);
        branch.writeBranch();
        System.out.println("A new branch " + branchName + " is created");
    }

    /**
     * delete specified branch
     */
    public static void deleteBranch(String branchName) throws IOException {
        if (!Branch.branchExist(branchName)) {
            System.out.println("Branch " + branchName + " not exists");
            return;
        }
        if (Branch.getCurrentBranchName().equals(branchName)) {
            System.out.println("error: Cannot delete branch " + branchName + " checked out at " + Repository.getWorkTree());
            return;
        }
        FileDeletion.deleteFile(Branch.path + File.separator + branchName);
    }
}